package com.yuehuanghun.framework.web;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * 请求上下文异常持有者
 * @author yuehuanghun
 * @date 2019年5月31日 上午9:20:06
 */
public class RequestContextExceptionHolder {
    private static String EXCEPTION_CONTEXT_ATTRIBUTE = "EXCEPTION_CONTEXT";
    
    public static void setException(Exception ex) {
        RequestContextHolder.currentRequestAttributes().setAttribute(EXCEPTION_CONTEXT_ATTRIBUTE, ex, RequestAttributes.SCOPE_REQUEST);
    }
    
    public static String getExceptionMessage() {
        Exception exception = getException();
        if(exception == null) {
            return null;
        }
        return exception.getMessage();
    }
    
    public static Exception getException() {
        return (Exception) RequestContextHolder.currentRequestAttributes().getAttribute(EXCEPTION_CONTEXT_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
    }
}
